package admission.ecnu.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class DBConnection {

	private static Logger logger = Logger.getLogger(DBConnection.class
			.getName());
	private static Context context = null; 
	private static DataSource dataSource = null; 
	private static int connCounter=0;
	private static int connCounterFree=0;
	
	
	/**
	 * 
	 * @return
	 */
	public synchronized static Connection getConnection() {
		try 
		{
			if(null == context)
			{
				context = new InitialContext();
				dataSource = (DataSource) context.lookup("java:comp/env/jdbc/test");
			}
			
			Connection conn = dataSource.getConnection();			
			if (conn != null)
			{
				System.out.println("got a new connection, no is " + (++connCounter));
				return conn;
			}
			else
				logger.fatal("DB connection error!!!");
		} catch (NamingException e) {
			logger.error(e.toString());
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error(e.toString());
		}
		return null;
	}

	/**
	 * 
	 * @param conn
	 */
	public static void closeConnection(Connection conn) {
		try {
			if (conn != null)
			{
				conn.close();
				System.out.println("free a connection, no is " + (++connCounterFree));
			}
		} catch (SQLException e) {
			logger.error(e.toString());
		}
	}
}
